# -*- coding: utf-8 -*-
"""
多业态支持模块 - 任务2.2
负责业态切换功能和业态数据管理
"""

import logging
from typing import Dict, Any, List, Optional, Set
from datetime import datetime
from enum import Enum


class BusinessTypeStatus(Enum):
    """业态状态枚举"""
    PENDING = "pending"      # 待处理
    PROCESSING = "processing"  # 处理中
    COMPLETED = "completed"   # 已完成
    FAILED = "failed"        # 失败
    SKIPPED = "skipped"      # 跳过


class BusinessTypeManager:
    """业态管理器"""
    
    def __init__(self):
        self.logger = logging.getLogger(__name__)
        
        # 业态配置
        self.business_types = {
            '餐饮': {
                'code': '11',
                'display_name': '餐饮美食',
                'keywords': ['餐饮', '餐厅', '饭店', '小吃', '快餐', '火锅', '咖啡', '茶饮'],
                'expected_fields': ['contact_person', 'contact_info', 'acceptable_rent', 'building_area']
            },
            '零售': {
                'code': '15',
                'display_name': '百货超市',
                'keywords': ['零售', '超市', '便利店', '服装', '百货', '商店'],
                'expected_fields': ['contact_person', 'contact_info', 'acceptable_rent', 'building_area']
            },
            '娱乐': {
                'code': '14',
                'display_name': '休闲娱乐',
                'keywords': ['娱乐', 'KTV', '网吧', '游戏', '休闲', '健身'],
                'expected_fields': ['contact_person', 'contact_info', 'acceptable_rent', 'building_area']
            }
        }
        
        # 业态状态跟踪
        self.business_type_status = {}
        self.business_type_history = []
        self.current_business_type = None
        self.session_data = {}  # 会话级别的业态数据隔离
        
        # 统计信息
        self.business_type_stats = {}
        
        self.logger.info("业态管理器初始化完成")
    
    def get_supported_business_types(self) -> List[str]:
        """获取支持的业态列表"""
        return list(self.business_types.keys())
    
    def get_business_type_config(self, business_type: str) -> Optional[Dict[str, Any]]:
        """获取业态配置"""
        return self.business_types.get(business_type)
    
    def get_business_type_code(self, business_type: str) -> str:
        """获取业态代码"""
        config = self.business_types.get(business_type)
        return config['code'] if config else '11'
    
    def get_business_type_display_name(self, business_type: str) -> str:
        """获取业态显示名称"""
        config = self.business_types.get(business_type)
        return config['display_name'] if config else business_type
    
    def switch_business_type(self, business_type: str) -> bool:
        """切换业态"""
        try:
            if business_type not in self.business_types:
                self.logger.error(f"不支持的业态: {business_type}")
                return False
            
            # 记录切换历史
            switch_record = {
                'from_type': self.current_business_type,
                'to_type': business_type,
                'switch_time': datetime.now(),
                'success': True
            }
            
            # 更新当前业态
            previous_type = self.current_business_type
            self.current_business_type = business_type
            
            # 初始化业态状态
            if business_type not in self.business_type_status:
                self.business_type_status[business_type] = BusinessTypeStatus.PENDING
            
            # 初始化业态数据存储
            if business_type not in self.session_data:
                self.session_data[business_type] = {
                    'raw_data': [],
                    'processed_data': [],
                    'start_time': datetime.now(),
                    'page_count': 0,
                    'error_count': 0
                }
            
            # 记录历史
            self.business_type_history.append(switch_record)
            
            self.logger.info(f"业态切换成功: {previous_type} -> {business_type}")
            return True
            
        except Exception as e:
            self.logger.error(f"业态切换失败: {e}")
            # 记录失败的切换
            switch_record = {
                'from_type': self.current_business_type,
                'to_type': business_type,
                'switch_time': datetime.now(),
                'success': False,
                'error': str(e)
            }
            self.business_type_history.append(switch_record)
            return False
    
    def set_business_type_status(self, business_type: str, status: BusinessTypeStatus):
        """设置业态状态"""
        if business_type in self.business_types:
            self.business_type_status[business_type] = status
            self.logger.debug(f"业态状态更新: {business_type} -> {status.value}")
    
    def get_business_type_status(self, business_type: str) -> BusinessTypeStatus:
        """获取业态状态"""
        return self.business_type_status.get(business_type, BusinessTypeStatus.PENDING)
    
    def add_business_type_data(self, business_type: str, data: List[Dict[str, Any]], data_type: str = 'raw'):
        """添加业态数据"""
        if business_type not in self.session_data:
            self.session_data[business_type] = {
                'raw_data': [],
                'processed_data': [],
                'start_time': datetime.now(),
                'page_count': 0,
                'error_count': 0
            }
        
        if data_type == 'raw':
            self.session_data[business_type]['raw_data'].extend(data)
        elif data_type == 'processed':
            self.session_data[business_type]['processed_data'].extend(data)
        
        self.logger.debug(f"添加 {business_type} 业态数据: {len(data)} 条 ({data_type})")
    
    def get_business_type_data(self, business_type: str, data_type: str = 'raw') -> List[Dict[str, Any]]:
        """获取业态数据"""
        if business_type not in self.session_data:
            return []
        
        if data_type == 'raw':
            return self.session_data[business_type]['raw_data']
        elif data_type == 'processed':
            return self.session_data[business_type]['processed_data']
        
        return []
    
    def increment_page_count(self, business_type: str):
        """增加页面计数"""
        if business_type in self.session_data:
            self.session_data[business_type]['page_count'] += 1
    
    def increment_error_count(self, business_type: str):
        """增加错误计数"""
        if business_type in self.session_data:
            self.session_data[business_type]['error_count'] += 1
    
    def validate_business_type_data(self, business_type: str, data: List[Dict[str, Any]]) -> Dict[str, Any]:
        """验证业态数据"""
        try:
            config = self.business_types.get(business_type)
            if not config:
                return {'valid': False, 'error': f'未知业态: {business_type}'}
            
            validation_result = {
                'valid': True,
                'total_count': len(data),
                'valid_count': 0,
                'invalid_count': 0,
                'business_type_accuracy': 0.0,
                'field_completeness': {},
                'issues': []
            }
            
            expected_fields = config['expected_fields']
            keywords = config['keywords']
            
            field_counts = {field: 0 for field in expected_fields}
            business_type_matches = 0
            
            for item in data:
                is_valid = True
                
                # 检查业态标识准确性
                item_business_type = item.get('business_type', '').lower()
                if any(keyword.lower() in item_business_type for keyword in keywords):
                    business_type_matches += 1
                
                # 检查字段完整性
                for field in expected_fields:
                    if item.get(field):
                        field_counts[field] += 1
                
                if is_valid:
                    validation_result['valid_count'] += 1
                else:
                    validation_result['invalid_count'] += 1
            
            # 计算业态准确性
            if len(data) > 0:
                validation_result['business_type_accuracy'] = business_type_matches / len(data) * 100
                
                # 计算字段完整性
                for field in expected_fields:
                    validation_result['field_completeness'][field] = field_counts[field] / len(data) * 100
            
            self.logger.info(f"{business_type} 业态数据验证完成: {validation_result}")
            return validation_result
            
        except Exception as e:
            self.logger.error(f"业态数据验证失败: {e}")
            return {'valid': False, 'error': str(e)}
    
    def generate_business_type_stats(self) -> Dict[str, Any]:
        """生成业态统计信息"""
        stats = {
            'session_summary': {
                'total_business_types': len(self.session_data),
                'current_business_type': self.current_business_type,
                'switch_count': len(self.business_type_history),
                'session_start_time': min([data['start_time'] for data in self.session_data.values()]) if self.session_data else None
            },
            'business_type_details': {},
            'switch_history': self.business_type_history,
            'status_summary': {}
        }
        
        # 业态详细统计
        for business_type, data in self.session_data.items():
            stats['business_type_details'][business_type] = {
                'raw_data_count': len(data['raw_data']),
                'processed_data_count': len(data['processed_data']),
                'page_count': data['page_count'],
                'error_count': data['error_count'],
                'start_time': data['start_time'],
                'status': self.business_type_status.get(business_type, BusinessTypeStatus.PENDING).value
            }
        
        # 状态汇总
        status_counts = {}
        for status in self.business_type_status.values():
            status_counts[status.value] = status_counts.get(status.value, 0) + 1
        stats['status_summary'] = status_counts
        
        return stats
    
    def reset_session(self):
        """重置会话"""
        self.business_type_status.clear()
        self.business_type_history.clear()
        self.current_business_type = None
        self.session_data.clear()
        self.business_type_stats.clear()
        self.logger.info("业态管理器会话已重置")
    
    def get_current_business_type(self) -> Optional[str]:
        """获取当前业态"""
        return self.current_business_type
    
    def is_business_type_completed(self, business_type: str) -> bool:
        """检查业态是否已完成"""
        status = self.get_business_type_status(business_type)
        return status == BusinessTypeStatus.COMPLETED
    
    def get_incomplete_business_types(self) -> List[str]:
        """获取未完成的业态列表"""
        incomplete = []
        for business_type in self.business_types.keys():
            if not self.is_business_type_completed(business_type):
                incomplete.append(business_type)
        return incomplete
    
    def apply_business_type_specific_processing(self, business_type: str, data: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
        """应用业态特定的数据处理逻辑"""
        try:
            processed_data = []
            
            for item in data:
                processed_item = item.copy()
                
                # 确保业态标识正确
                processed_item['business_type'] = business_type
                
                # 业态特定处理
                if business_type == '餐饮':
                    processed_item = self._process_catering_data(processed_item)
                elif business_type == '零售':
                    processed_item = self._process_retail_data(processed_item)
                elif business_type == '娱乐':
                    processed_item = self._process_entertainment_data(processed_item)
                
                processed_data.append(processed_item)
            
            self.logger.debug(f"{business_type} 业态特定处理完成: {len(processed_data)} 条")
            return processed_data
            
        except Exception as e:
            self.logger.error(f"业态特定处理失败: {e}")
            return data
    
    def _process_catering_data(self, item: Dict[str, Any]) -> Dict[str, Any]:
        """处理餐饮业态特定数据"""
        # 餐饮业态可能有特殊的租金模式
        rent = item.get('acceptable_rent', '')
        if '转让费' in rent:
            item['has_transfer_fee'] = True
        
        return item
    
    def _process_retail_data(self, item: Dict[str, Any]) -> Dict[str, Any]:
        """处理零售业态特定数据"""
        # 零售业态可能关注客流量
        title = item.get('title', '')
        if '客流' in title or '人流' in title:
            item['mentions_foot_traffic'] = True
        
        return item
    
    def _process_entertainment_data(self, item: Dict[str, Any]) -> Dict[str, Any]:
        """处理娱乐业态特定数据"""
        # 娱乐业态可能有特殊的营业时间要求
        title = item.get('title', '')
        if '夜场' in title or '24小时' in title:
            item['extended_hours'] = True
        
        return item
